import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { plainToInstance } from 'class-transformer';
import { Readable } from 'stream';
import { Repository } from 'typeorm';
import { FileMetadata, MediaType } from '../minio/dto/media-file-options.dto';
import { MinioService } from '../minio/minio.service';
import { CreateMediaDto } from './dto/create-media.dto';
import { UpdateMediaDto } from './dto/update-media.dto';
import { Media } from './entities/media.entity';

@Injectable()
export class MediaService {
  constructor(
    @InjectRepository(Media)
    private readonly mediaRepo: Repository<Media>,
    private readonly minioService: MinioService,
  ) {
    console.log(minioService);
    console.log(mediaRepo);
  }

  async create(
    createMediaDto: CreateMediaDto & {
      executorId: string;
      file: Buffer | Readable;
    },
  ) {
    const { file, executorId, ...restCreateMediaDto } = createMediaDto;
    const metadata = await this.minioService.upload(file, {
      type: MediaType.IMAGE,
      public: true,
    });

    const media = new Media();
    Object.entries({
      name: restCreateMediaDto.name,
      type: restCreateMediaDto.type,
      ownerId: executorId,
      metadata: plainToInstance(FileMetadata, metadata),
      createdAt: new Date().toISOString(),
      editAt: new Date().toISOString(),
    }).forEach(([k, v]) => {
      media[k] = v;
    });

    this.mediaRepo.create(media);

    return this.mediaRepo.save(media);
  }

  findAll() {
    return `This action returns all media`;
  }

  findOne(id: number) {
    return `This action returns a #${id} media`;
  }

  update(id: number, updateMediaDto: UpdateMediaDto) {
    return `This action updates a #${id} media`;
  }

  remove(id: number) {
    return `This action removes a #${id} media`;
  }
}
